<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Models\Order;
use App\Models\Option;
use App\Repositories\MemberRepositoryEloquent;

class SettlementCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'order:settlement';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '订单结算';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct(MemberRepositoryEloquent $user)
    {
        parent::__construct();
        $this->user = $user;
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        //
        //while(1){
        //for($i = 0; $i < 120; $i++){
            $orders = Order::where('close_time','<=',time())->where('status','=',0)->get();
            if($orders){
                foreach ($orders as $key => $order) {
                    
                    //$optionData = get_option_data($order->symbol);
                    $optionData = get_settle_option_data($order->symbol,date('Y-m-d H:i:s',$order->close_time));
                    //var_dump($optionData);
                    if($optionData){
                        $order->status=1;
                        $order->close_point =$optionData['last_price'];
                        $spare = $optionData['last_price']-$order->buy_point;
                        if($spare>0){
                            //涨
                            $profit = $order->direction==1?($order->amount*(1+$order->rate)):(-$order->amount);
                        }elseif($spare==0){
                            //平
                            $profit = 0;
                            //$profit = $order->amount;
                        }else{
                            //跌
                            $profit = $order->direction==0?($order->amount*(1+$order->rate)):(-$order->amount);
                        }
                        
                        // if($profit<0){
                        //     $profit=0;
                        // }

                        $order->profit = $profit;
                        $res = $order->save();
                        if($res && $profit>0){
                            $note = '订单('.$order->orderno.')盈亏';
                            $this->user->modifyBalance($order->user_id,$profit,4,$note);
                        }
                        if($res && $profit==0){
                            $note = '订单('.$order->orderno.')无盈亏，返还本金';
                            $this->user->modifyBalance($order->user_id,$profit,5,$note);
                        }
                        
                    }
                }
            }
            //sleep(0.5); // 暂停2秒
            //usleep(5000); // 暂停2秒
        //}
        //}
    }
}
